#include <stdlib.h>
#include <assert.h>
#include "SeqList.h"

struct SeqList Create (int iSize){
	struct SeqList list;
	list.pDatas=(DataElem *)malloc(iSize * sizeof (DataElem));
	list.iLength=0;
	list.iSize=iSize;
	if(list.pDatas==NULL){
		list.iSize=0;
	}
	return list;
};

void Clear(struct SeqList * pSeqList){
	pSeqList->iLength=0;
}

void Destroy(struct SeqList * pSeqList){
	free(pSeqList->pDatas);
	pSeqList->pDatas=NULL;
	pSeqList->iSize=0;
}
struct SeqList Copy (struct SeqList srcSeqList){
	struct SeqList destSeqList;
	destSeqList=Create(srcSeqList.iSize);
	if(destSeqList.pDatas==NULL)
		return destSeqList;
	int i;
	for(i=0;i<srcSeqList.iLength;++i){
		destSeqList.pDatas[i]=srcSeqList.pDatas[i];
	}
	destSeqList.iLength=i;
	return destSeqList;
};

int IsEmpty(struct SeqList list){
	return(list.iLength==0);
}

int Length(struct SeqList list){
	return list.iLength;
}

Position BeginPosition(struct SeqList list){
	return list.pDatas;
}

Position EndPosition(struct SeqList list){
	return list.pDatas+list.iLength;
}

Position NextPosition(struct SeqList list,Position pos){
	return pos+1;
}

Position LocatePosition(struct SeqList list,int i){
	if(i>=1&&i<=list.iLength){
		return list.pDatas+(i-1);
	}
	return list.pDatas+list.iLength;
}

Position LocateElem(struct SeqList list,DataElem e){
	int i;
	for(i=0;i<list.iLength;++i){
		if(list.pDatas[i]==e){
			return list.pDatas+i;
		}
	}
	return list.pDatas+list.iLength;
}

DataElem GetElem(struct SeqList list , Position pos){
	assert(pos!=EndPosition(list));
	return * pos;
}

void SetElem(struct SeqList list ,Position pos,DataElem e){
	assert(pos!=EndPosition(list));
	*pos=e;
}

int InsertBefore(struct SeqList * pSeqList,Position pos,DataElem e){
	if(pSeqList->iSize==pSeqList->iLength){
		struct SeqList newSeqList=Create(2*pSeqList->iSize);
		if(newSeqList.pDatas==NULL){
			return 0;
		}
		int i;
		for(i=0;i<pSeqList->iLength;++i){
			newSeqList.pDatas[i]=pSeqList->pDatas[i];
		}
		newSeqList.iLength=i;
		pos=newSeqList.pDatas+(pos-pSeqList->pDatas);
		Destroy(pSeqList);
		* pSeqList=newSeqList;
	}
	assert(pSeqList->iSize>pSeqList->iLength);
	Position lastPos=pSeqList->pDatas+pSeqList->iLength;
	while(pos!=lastPos){
		*lastPos=*(lastPos-1);
		--lastPos;
	}
	*pos=e;
	++pSeqList->iLength;
	return 1;
	
}

void Delete(struct SeqList *pSeqList ,Position pos){
	Position endPos=EndPosition(*pSeqList);
	assert (pos!=endPos);
	++pos;
	while(pos!=endPos){
		*(pos-1)=*pos;
		++pos;
	}
	--pSeqList->iLength;
}
